#include "RR.h"
#include <stdio.h>
#include <stdlib.h>

/**
 * 函数: calculateTimes
 * 功能: 根据时间片轮转调度算法计算每个进程的完成时间、周转时间和等待时间
 *
 * 参数:
 *  - processes: 指向包含多个进程信息的数组
 *  - n: 进程数量
 *  - time_slice: 时间片长度
 *
 * 描述:
 *  计算进程的完成时间，周转时间和等待时间并存在结构体中即可
 */

int isFinished(Process *processes, int n) {
	for (int i = 0; i < n; i++) {
		if (processes[i].remaining_time > 0) return 0;
	}
	return 1;
}

void
calculateTimes (Process *processes, int n, int time_slice)
{
	int curr_pid = 0, curr_time = 0;
	while(!isFinished(processes, n)) {
		if (processes[curr_pid].remaining_time > 0) {
			if (processes[curr_pid].remaining_time > time_slice) {
				processes[curr_pid].remaining_time -= time_slice;
				curr_time += time_slice;
			}
			else {
				curr_time += processes[curr_pid].remaining_time;
				processes[curr_pid].remaining_time = 0;
				processes[curr_pid].completion_time = curr_time;
				processes[curr_pid].turnaround_time = processes[curr_pid].completion_time - processes[curr_pid].arrival_time;
				processes[curr_pid].waiting_time = processes[curr_pid].turnaround_time - processes[curr_pid].burst_time;
			}
		}
		curr_pid = (curr_pid + 1) % n;
	}
}
